(function($) {
	$.LocationSelect = {
		heBingDefault:{},//合并之后的 default
		heBingSpec:{},
		defaults : {
				data: "area-all.json",
				autoDetect : false,    //是否通过google定位
				areaCode:""   //有值就会默认选中
		},
		
		build : function(user_opts) {
			var options = $.extend($.LocationSelect.defaults, user_opts);
			$.LocationSelect.heBingDefault = options;
			return $(this).each(function() {
				var specs = {
					holder : $(this),
					selectors: {},
					_province : "",
					_city : "",
					_street:"",
					_pCode : "",
					_cCode : "",
					opts : options
				};
				//console.log(options);
				//specs.holder.append('<select name="province" id="province" style="width:100px;"><option value="0">选择省</option></select>   <select name="city" id="city" style="width:100px;"><option value="0">选择市</option></select>   <select name="district" id="district" style="width:100px;"><option value="0">选择地区</option></select>');
				try{
					
					$.LocationSelect.init(specs);
				} catch(e) {
					setTimeout(function() {
						$.LocationSelect.init(specs);
					},1000);
				}
			});
		},
		data : {
			province : [],
			city: [],
			district: [],
			street:[]
		},
		init: function(specs){
			
		    specs.selectors.province = specs.holder.find("select[name='province']");
		    specs.selectors.city = specs.holder.find("select[name='city']");
		    specs.selectors.district = specs.holder.find("select[name='district']");
		    specs.selectors.street = specs.holder.find("select[name='street']");
			$.getJSON(specs.opts.data, function(data){
			    $.LocationSelect.data.province = data.province;
			    $.LocationSelect.data.district = data.district;
			    $.LocationSelect.data.city = data.city;
			    $.LocationSelect.data.street = data.street;
			    
			    $(specs.selectors.city).change(function(evt){
			        fetch(evt.target);
			    });
			    $(specs.selectors.province).change(function(evt){
			        fetch(evt.target);
			    });
			    $(specs.selectors.district).change(function(evt){
			        fetch(evt.target);
			    });
			    $.each($.LocationSelect.data.province, function(i, item){
			        var str = "<option value='" + item.code + "'>" + item.name + "</option>";
			        specs.selectors.province.append(str);
			    });
			    
			    if(specs.opts.autoDetect) {
			    	$.LocationSelect.setDefaultLocation(specs);
			    }
			    
			    if(specs.opts.areaCode!=""){
			    	$.LocationSelect.setSelect(specs);
			    }
			});
		    function fetch(target){
		        var _start, //leading string of code
					 _result = new Array(), //filtered result array
					 _d, //data to be inserted
					 _s, //the selector that requested the fetching
					 _o, //html string of default option element
					 n = target.value;//value of option code in the former select element
		 		
		        if (len(n) == 2) {//省份 获取 城市信息
		        	console.log(n);
		            _start = n.substring(0, 2);
		            _s = specs.selectors.city;
		            _d = $.LocationSelect.data.city;
		            /*
		            if (!specs._pCode || !specs._cCode) {
		                _o = "<option value='0'>请选择一个城市</option>";
		            }*/
		            $(specs.selectors.district).find("option[value!='0']").remove();
		            
		        }
		        else if(len(n) == 4){
		        	_s = specs.selectors.district;
		            _start = n.substring(0, 4);
		            _d = $.LocationSelect.data.district;
		            $(specs.selectors.street).find("option[value!='0']").remove();
		        }
		        else {// 城市 获取 区域信息
		            _s = specs.selectors.street;
		            _start = n;
		            _d = $.LocationSelect.data.street;
		            /*
		            if (!specs._pCode || !specs._cCode) {
		                _o = "<option value='0'>请选择一个区</option>";
		            }*/
		        }
		        $(_s).find("option[value!='0']").remove();
		        if (_o) 
		            $(_s).append(_o);
		        $.each(_d, function(i, item){
		            if (item.code.startsWith(_start)) {
		                _result.push(item);
		            }
		        });
		        $.each(_result, function(i, item){
		            var str = "<option value='" + _result[i].code + "'>" + _result[i].name + "</option>";
		            $(_s).append(str);
		        });
		         
		        function len(a){
		        	return a.length;
		        }
		        function zero(a){
		            
		            if (a) {
						var i = a.length, n = 0;
		                while (i > 0) {
		                    i--;
		                    if (a.charAt(i) == "0") 
		                        n++;
		                }
		            }
		            return n;
		        };
		    };
		},
		get: function(){
			//返回选中信息
		    var holder = $(this),
		    	province = holder.find("select[name='province']"),
		    	city = holder.find("select[name='city']"),
		    	district = holder.find("select[name='district']"),
		    	street = holder.find("select[name='street']"),
		    	info = {
		        "province": province.val() == 0 ? "" : province[0].options[province[0].selectedIndex].text,
		        "city": city.val() == 0 ? "" : city[0].options[city[0].selectedIndex].text,
		        "district": district.val() == 0 ? "" : district[0].options[district[0].selectedIndex].text,
		        "street": street.val() == 0 ? "" : street[0].options[street[0].selectedIndex].text
		    };
		    return info;
		},
		setSelect:function(specs){
			// 通过areaCode  反向选中 省市区
			var areaCode = specs.opts.areaCode;
			eachData(areaCode.substring(0, 2));
			eachData(areaCode.substring(0, 4));
			eachData(areaCode.substring(0, 6));
			eachData(areaCode);
			
			function eachData(areaCode){
				var result = []; 
				if (areaCode.length == 4) {//市区
		        	if(zero(areaCode.substring(2,4))<2){
		        		$("#city").val(areaCode);
		        		$.each($.LocationSelect.data.district, function(i, item){
		 		            if (item.code.startsWith(areaCode.substring(0,4))) {
		 		                result.push(item);
		 		            }
			 		     });
			        	$.each(result, function(i, item){
		 		            var str = "<option value='" + result[i].code + "'>" + result[i].name + "</option>";
		 		            $(specs.selectors.district).append(str);
			 		    });
		        	}else{
		        		 $.each($.LocationSelect.data.city, function(i, item){
		 		            if (item.code.startsWith(areaCode.substring(0,2))) {
		 		                result.push(item);
		 		            }
		 		        });
		        		$.each(result, function(i, item){
		 		            var str = "<option value='" + result[i].code + "'>" + result[i].name + "</option>";
		 		            $(specs.selectors.city).append(str);
		 		        });
		        	}	
		            
		        }
		        else if(areaCode.length == 2) {// 省级
		        	$("#province").val(areaCode);
		        	
		        	$.each($.LocationSelect.data.city, function(i, item){
	 		            if (item.code.startsWith(areaCode.substring(0,2))) {
	 		                result.push(item);
	 		            }
	 		        });
	        		$.each(result, function(i, item){
	 		            var str = "<option value='" + result[i].code + "'>" + result[i].name + "</option>";
	 		            $(specs.selectors.city).append(str);
	 		        });
		        }
		        else if(areaCode.length == 6) {//县级
		        	if(zero(areaCode.substring(4,6))<2){
		        		$("#district").val(areaCode);
		        	}else{
		        		 $.each($.LocationSelect.data.district, function(i, item){
		 		            if (item.code.startsWith(areaCode.substring(0,4))) {
		 		                result.push(item);
		 		            }
			 		     });
			        	$.each(result, function(i, item){
		 		            var str = "<option value='" + result[i].code + "'>" + result[i].name + "</option>";
		 		            $(specs.selectors.district).append(str);
			 		    });
		        	}
		        }
		        else {//街道
		        	
					$.each($.LocationSelect.data.street, function(i, item){
	 		            if (item.code.startsWith(areaCode)) {
	 		                result.push(item);
	 		            }
		 		     });
		        	$.each(result, function(i, item){
	 		            var str = "<option value='" + result[i].code + "'>" + result[i].name + "</option>";
	 		            $(specs.selectors.street).append(str);
		 		    });
		        	$("#street").val(areaCode);
				}
		        function zero(a){
		            if (a) {
						var i = a.length, n = 0;
		                while (i > 0) {
		                    i--;
		                    if (a.charAt(i) == "0") 
		                        n++;
		                }
		            }
		            return n;
		        };
			}
			
		}
	}
	
	$.fn.LocationSelect = $.LocationSelect.build;
	$.fn.getLocation = function(type){
		
		var retV = {};
		var province = $(this).find("select[name='province']");
		var city = $(this).find("select[name='city']");
		var district = $(this).find("select[name='district']");
    	if(district.val()!=0){
    		if(type=="all"){
    			return {"code":district.val(),"name":province.find("option:selected").text()+city.find("option:selected").text()+district.find("option:selected").text()};
        		
    		}else{
    			return {"code":district.val(),"province":province.find("option:selected").text(),"city":city.find("option:selected").text(),"district":district.find("option:selected").text()};
    		}
    	}else if(city.val()!=0){
    		if(type=="all"){
    			return {"code":city.val(),"name":province.find("option:selected").text()+city.find("option:selected").text()};
        		
    		}else{
    			return {"code":city.val(),"province":province.find("option:selected").text(),"city":city.find("option:selected").text(),"district":""};
    		}
    	}else if(province.val()!=0){
    		if(type=="all"){
    			return {"code":province.val(),"name":province.find("option:selected").text()};
    		}else{
    			return {"code":province.val(),"province":province.find("option:selected").text(),"city":"","district":""};
    		}
    	}else{
    		return {"code":"0","name":"","province":"","city":"","district":""};
    	}
	};
	if (!String.prototype.startsWith) {
	    String.prototype.startsWith = function(str){
	        if (str) 
	            return this.substring(0, str.length) == str;
	    };
	}
	
})(jQuery);